package com.agileai.portal.controller.wcm;

import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Iterator;
import java.util.List;

import javax.imageio.ImageIO;

import net.coobird.thumbnailator.Thumbnails;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.hotweb.annotation.PageAction;
import com.agileai.hotweb.controller.core.SimpleHandler;
import com.agileai.hotweb.renders.AjaxRenderer;
import com.agileai.hotweb.renders.ViewRenderer;
import com.agileai.portal.bizmoduler.wcm.WcmPictureGroup8ContentManage;

/**
 * generated by miscdp
 */
public class FileUploaderHandler extends SimpleHandler{
//	RES_ID,GRP_ID,RES_NAME,RES_LOCATION,RES_THUMB_LOCATION,RES_WIDTH,RES_HEIGHT,RES_SIZE,RES_SUFFIX
	private DataParam resourceParam = new DataParam();
	private String resourceRelativePath = null;
	
	public FileUploaderHandler(){
		super();
	}
	
	@SuppressWarnings("rawtypes")
	@PageAction
	public ViewRenderer uploadFile(DataParam param){
		String responseText = FAIL;
		try {
			DiskFileItemFactory fac = new DiskFileItemFactory();
			ServletFileUpload fileFileUpload = new ServletFileUpload(fac);
			fileFileUpload.setHeaderEncoding("utf-8");
			List fileList = null;
			fileList = fileFileUpload.parseRequest(request);

			Iterator it = fileList.iterator();
			String name = "";
			String fileFullPath = null;
			
			File filePath = null;
			while (it.hasNext()) {
				FileItem item = (FileItem) it.next();
				if (item.isFormField()){
					String fieldName = item.getFieldName();
					if (fieldName.equals("columnId")){
						String columnId = item.getString();
						resourceParam.put("GRP_ID",columnId);
						filePath = this.buildImapgeSavePath(columnId);						
					}
					continue;
				}
				name = item.getName();
				
				resourceParam.put("RES_NAME",name);
				String location = resourceRelativePath + "/" + name;
				resourceParam.put("RES_LOCATION",location);
				String thumbLocation = resourceRelativePath + "/thumbnail/"  + name;
				resourceParam.put("RES_THUMB_LOCATION",thumbLocation);
				
				fileFullPath = filePath.getAbsolutePath()+File.separator+name;
				long resourceSize = item.getSize();
				resourceParam.put("RES_SIZE",String.valueOf(resourceSize));
				String suffix = name.substring(name.lastIndexOf("."));
				resourceParam.put("RES_SUFFIX",suffix);
				File tempFile = new File(fileFullPath);
				if (!tempFile.getParentFile().exists()){
					tempFile.getParentFile().mkdirs();
				}
				item.write(tempFile);
				
				createThumbnail(tempFile);
				
				BufferedImage bufferedImage = ImageIO.read(tempFile);   
				String width = String.valueOf(bufferedImage.getWidth());
				String height = String.valueOf(bufferedImage.getHeight());
				resourceParam.put("RES_WIDTH",width);
				resourceParam.put("RES_HEIGHT",height);

				this.insertResourceRecord();
			}
			responseText = SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new AjaxRenderer(responseText);
	}

	public File buildImapgeSavePath(String columnId){
		File result = null;
		String contextRealPath = dispatchServlet.getServletConfig().getServletContext().getRealPath("");
		File contextFile = new File(contextRealPath);
		String parentAbsolutePath = contextFile.getParentFile().getAbsolutePath();
		WcmPictureGroup8ContentManage pictureGroup8ContentManage = this.lookupService(WcmPictureGroup8ContentManage.class);
		DataParam param = new DataParam("GRP_ID",columnId);
		DataRow row = pictureGroup8ContentManage.queryTreeRecord(param);
		String grpCode = row.stringValue("GRP_CODE");
		String imagesFilePath = parentAbsolutePath+File.separator+"HotServer"
				+File.separator+"reponsitory"+File.separator+"images"+File.separator+grpCode;
		
		resourceRelativePath = "/HotServer"+"/reponsitory"+"/images/"+grpCode;
		result = new File(imagesFilePath);
		return result;
	}
	
	public void insertResourceRecord(){
		WcmPictureGroup8ContentManage pictureGroup8ContentManage = this.lookupService(WcmPictureGroup8ContentManage.class);
		pictureGroup8ContentManage.createtContentRecord("WcmPictureResource", resourceParam);
		
	}
	
	public void createThumbnail(File srcFile){
		try {
			String imageName = srcFile.getName();
			File desFileDir = new File(srcFile.getParentFile().getAbsolutePath()+"/thumbnail/");
			if (!desFileDir.exists()){
				desFileDir.mkdirs();
			}
			File newDesFilew =  new File(desFileDir.getAbsolutePath()+"/"+imageName);
			Thumbnails.of(srcFile).size(126, 126).toFile(newDesFilew);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
